<?php
/**
 * Created by EditPlus.
 * User: GRAY <iamgray@gmail.com>
 * Date: 8/4/16
 * Time: 19:43
 */

namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;
use Common\Vendor\Hook\BaseHook;


class CrawlerController extends Controller {

    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    function gzdecode ($data) {
        $flags = ord(substr($data, 3, 1));
        $headerlen = 10;
        $extralen = 0;
        $filenamelen = 0;
        if ($flags & 4) {
            $extralen = unpack('v' ,substr($data, 10, 2));
            $extralen = $extralen[1];
            $headerlen += 2 + $extralen;
        }
        if ($flags & 8) // Filename
            $headerlen = strpos($data, chr(0), $headerlen) + 1;
        if ($flags & 16) // Comment
            $headerlen = strpos($data, chr(0), $headerlen) + 1;
        if ($flags & 2) // CRC at end of file
            $headerlen += 2;
        $unpacked = @gzinflate(substr($data, $headerlen));
        if ($unpacked === FALSE)
            $unpacked = $data;
        return $unpacked;
    }
    //电商报告（暂不支持）
    public function b2bReport() {
        $post_data = file_get_contents('php://input');
        $type = 2; //类型 1运营商 2淘宝 3京东
        $data_type = 2; //数据类型 1原始数据 2报告
        $this->into_db($post_data,$type,$data_type);
    }
    //电商原始数据
    public function b2bRawData() {
        $post_data = file_get_contents('php://input');
        $type = 2;
        $data_type = 1;
        $this->into_db($post_data,$type,$data_type);
    }
    //运营商报告
    public function mobileReport() {
        $post_data = file_get_contents('php://input');
        $type = 1;
        $data_type = 2;
        $this->into_db($post_data,$type,$data_type);
    }
    //运营商原始数据
    public function mobileRawData() {
        $post_data = file_get_contents('php://input');
        $type = 1;
        $data_type = 1;
        $this->into_db($post_data,$type,$data_type);
    }

    public function into_db($post_data,$type,$data_type) {

        if($post_data<>'') {
            $data = $this->gzdecode(base64_decode($post_data));
            //Log::write('爬虫数据:'.$data , Log::DEBUG);
            //$data =  stripslashes(substr( substr($data, 1),0,-1));
            $data =  stripslashes($data);
            $data_arr = json_decode($data,true);
            if($data_arr) {
                if($data_type==1) {
                    //原始数据
                    $get_type = $data_arr['type'];
                    $id_num = $data_arr['identity_card_number'];
                    $trade_no = $data_arr['push_data'][0]['token'];
                    $name = $data_arr['name'];
                    $mobile =  $data_arr['cell_phone_number'];
                    $website =  $data_arr['website'];
                }
                if($data_type==2) {
                    //报告数据
                    $get_type = $data_arr['type'];
                    $id_num = $data_arr['identity_card_number'];
                    $trade_no = $data_arr['push_data']['report']['token'];
                    $name =  $data_arr['name'];
                    $mobile =  $data_arr['cell_phone_number'];
                    $website =  $data_arr['website'];
                }
            }
            if($get_type<>'') {
                $sql_data = array(
                    'id_num' => $id_num,
                    'name'=> $name,
                    'mobile'=> $mobile,
                    'trade_no'=> $trade_no,
                    'post_data' => '',//$data,//  数据太大暂时不存
                    'data_type' => $data_type,
                    'type' => $type,
                    'website'=>$data_arr['website'],
                    'add_time' => time(),
                );
                ////////////////////////////////////////
                $Cid=M('Cutomer')->field('id,mobile')->where(['mobile'=>$mobile])->find();
                $ar_=M('CustomerAuth')->where(['customer_id'=>$Cid['id'],'china_mobile'=>0])->find();
                if($ar_){
                    $ar=M('CustomerAuth')->where(['customer_id'=>$Cid['id'],'china_mobile'=>0])->setField(['china_mobile'=>1]);
                    /*****************************重新认证之后要清除逾期状态****************************************/
                    // $cust = M('Customer')->where(['id'=>$Cid['id']])->find();
                    // if($cust['accreditation_status'] ==1 && !empty($cust['sesame_score']) ){
                    //     $data1 = [
                    //         'accreditation_status'=>0
                    //     ] ;
                    //     Log::rong_write("*******customerFewMsg|". $Cid['id'] ."accreditation_status|字段清零*******：");
                    //     $saveRes = M('Customer')->where(['id'=>$Cid['id']])->save($data1);
                    //     Log::rong_write("*******customerFewMsg|accreditation_status|字段清零结果|". $saveRes ."*******：");
                    // }
                    /*****************************重新认证之后要清除逾期状态****************************************/
                    $ar_res=M('CustomerAuth')->where(['customer_id'=>$Cid['id']])->find();
                    // 控制器 用户id 操作|yunyings完了|更改认证|结果|findchirna
                  Log::mobile_write("++++++++++++++++++用户".$Cid['id']."进行运营商重新认证|结果：".$ar."|".json_encode($ar_res).'|执行语句'.M('CustomerAuth')->getLastSql().'|');

                }



                Log::mobile_write("---运营商数据|用户.".$Cid['id'].json_encode($ar));
                $result = '{"success":true,"message":"接收数据成功"}';
                ///////////////////////////////////////////////
                $insertId = M('CertificateData')->add($sql_data);
                Log::mobile_write("---运营商数据|入库|数据:".json_encode($sql_data).'|运行语句'.M('CertificateData')->getLastSql().'|运行结果:'.$insertId);
                if($insertId>0) {
                    $CustomerID = M('Customer')->where(['id_num' => $id_num])->getField('id');
                    $auth_id = M('CustomerAuth')->where(['customer_id' => $CustomerID])->getField('id');
                    Log::mobile_write("---用户id:".$CustomerID.'|用户认证表id'.$auth_id);
                    if(!$auth_id) {
                        if($CustomerID>0) {
                            $data = array(
                                'customer_id' => $CustomerID,
                                'id_num'=>1,
                                'face_pass'=>1
                            );
                            M('CustomerAuth')->add($data);
                            Log::mobile_write("---如果用户认证表没有，插入数据:".json_encode($data).'|插入语句'.M('CustomerAuth')->getLastSql());
                        }
                    }
                    if($CustomerID>0) {
                        Log::mobile_write("---用户id>0:".$CustomerID);
                        if(substr($website,0,5) =='china') {
                            $sqldata = array('china_mobile'=>1);
                            Log::mobile_write("---用户id>0:".$CustomerID."截取运营商认证字段:".substr($website,0,5)."数据".json_encode($sqldata));
                        } elseif($website =='taobao') {
                            $sqldata = array('taobao_pass'=>1);
                            Log::mobile_write("---用户id>0:".$CustomerID."截取淘宝字段:".$website."数据".json_encode($sqldata));
                        } elseif($website =='jingdong') {
                            $sqldata = array('jd_pass'=>1);
                            Log::mobile_write("---用户id>0:".$CustomerID."截取京东字段:".$website."数据".json_encode($sqldata));

                        } else {
                            $sqldata = false;
                        }
                        if($sqldata) {
                            $arr=M('CustomerAuth')->where(['customer_id'=>$CustomerID])->setField($sqldata);
                            $data_res=M('CustomerAuth')->field('id,customer_id,id_num,face_pass,china_mobile')->where(['customer_id'=>$CustomerID])->find();
                            Log::mobile_write("---用户id:".$CustomerID."修改用户认证数据".json_encode($sqldata)."|用户ID".$CustomerID."|sql:".M('CustomerAuth')->getLastSql()."|结果".$arr."|".json_encode($data_res));
                            Log::mobile_write("---用户id:".$CustomerID."修改用户认证数据".json_encode($sqldata)."|用户ID".$CustomerID."|sql:".M('CustomerAuth')->getLastSql()."|结果".$arr);
                        }
                    }
                    $Cid=M('Cutomer')->field('id,mobile')->where(['mobile'=>$mobile])->find();
                    $C_=M('CutomerAuth')->field('id,customer_id,china_mobile')->where(['customer_id'=>$Cid['id'],'china_mobile'=>0])->find();

                    if($C_){
                        $ar=M('CustomerAuth')->where(['customer_id'=>$Cid['id']])->setField(['china_mobile'=>1]);

                    }
                    Log::mobile_write("---运营商数据|用户.".$Cid['id'].json_encode($ar));
                    $result = '{"success":true,"message":"接收数据成功"}';
                    Log::write('爬虫数据结果:'.$result , Log::DEBUG);
                    echo $result;
                } else {
                    $Cid=M('Cutomer')->field('id,mobile')->where(['mobile'=>$mobile])->find();
                    $C_=M('CutomerAuth')->field('id,customer_id,china_mobile')->where(['customer_id'=>$Cid['id'],'china_mobile'=>0])->find();

                    if($C_){
                        $ar=M('CustomerAuth')->where(['customer_id'=>$Cid['id']])->setField(['china_mobile'=>1]);

                    }
                    Log::mobile_write("---运营商数据|用户.".$Cid['id'].json_encode($ar));
                    $result = '{"success":false,"message":"写入数据库失败"}';
                    Log::write('爬虫数据结果:'.$result , Log::DEBUG);
                    echo $result;
                }
            } else {
                $result = '{"success":false,"message":"数据解析失败"}';
                Log::write('爬虫数据结果:'.$result , Log::DEBUG);
                echo $result;
            }

        } else  {
            $result = '{"success":false,"message":"POST数据为空"}';
            Log::write('爬虫数据结果:'.$result , Log::DEBUG);
            echo $result;
        }
    }
}
